package io.renren.modules.udp.utils;

public class UdpStringUtils {

	public static byte[] hexStr2Bytes(String src) {
		String sSrcHex = src.replace(" ", "");
		int l = sSrcHex.length() / 2;
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			ret[i] = (byte) Integer.valueOf(sSrcHex.substring(i * 2, i * 2 + 2), 16).byteValue();
		}
		return ret;
	}

	public static String bytes2Str(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv.toUpperCase()+" ");
		}
		return stringBuilder.toString().trim();
	}

	public static String str2ASCII(int nReqLength,String src) {

		StringBuilder sb = new StringBuilder();
		char[] ch = src.toCharArray();
		for (int i = 0; i < ch.length; i++) {

			sb.append(Integer.toHexString(Integer.valueOf(ch[i]).intValue())).append(" ");// 加空格
			// sb.append(Integer.valueOf(ch[i]).intValue());// 不加空格
		}
		if(nReqLength>src.length()){
			StringBuffer sbreq = new StringBuffer();
			for(int j=0;j<nReqLength-src.length();j++){
				sbreq.append(Integer.toHexString(Integer.valueOf(' ').intValue())).append(" ");
			}
			return sb.toString()+sbreq.toString();
		}
		return sb.toString();
	}

	public static String hexStrToStr(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }



}
